package com.valuedaas.schoolsafety.common.filter;

import com.alibaba.fastjson.JSON;
import com.valuedaas.schoolsafety.common.Constants;
import com.valuedaas.schoolsafety.controller.user.vo.User;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 请求记录
 *
 * @author chenhua
 */
@Component
@WebFilter(filterName = "loggingFilter", urlPatterns = "*.do")
@Order(3)
public class LoggingFilter extends OncePerRequestFilter {

    static final Logger LOG = LoggerFactory.getLogger(LoggingFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        HttpServletRequest httpReq = ((HttpServletRequest) request);
        HttpServletResponse httpResp = ((HttpServletResponse) response);

        String uri = httpReq.getRequestURI();
        long start = System.currentTimeMillis();
        Document reqLog = new Document();
        reqLog.append("uri", uri);

        User user = getSessionUser(httpReq);
        if (user != null) {
            reqLog.append("user", user.getNickname() + "-" + user.getUserId());
        } else {
            reqLog.append("user", "null");
        }

        Map<String, String[]> params = httpReq.getParameterMap();
        List<Document> pList = new ArrayList<>();
        for (Entry<String, String[]> param : params.entrySet()) {
            pList.add(new Document(param.getKey(), param.getKey().equals("password") ? "******" : param.getValue()));
        }
        chain.doFilter(httpReq, httpResp);

        reqLog.append("params", pList);
        reqLog.append("spendMs", System.currentTimeMillis() - start);
        // int status = ((HttpServletResponse) response).getStatus();
        // reqLog.append("STATUS", status);
        // reqLog.append("resp",
        // IOUtils.toString(responseWrapper.getContentInputStream(), "utf-8"));
        LOG.info(JSON.toJSONString(reqLog));
    }

    private User getSessionUser(HttpServletRequest httpReq) {
        Object obj = httpReq.getSession().getAttribute(Constants.SESSION_KEY);
        if (obj == null) {
            return null;
        }
        if (obj instanceof User) {
            return (User) obj;
        }
        return null;
    }

}